package com.service.login.task;

import com.service.config.utils.IdUtil;
import com.service.config.utils.JsonXMLUtils;
import com.service.config.utils.RedisUtil;
import com.alibaba.fastjson.JSONArray;
import com.service.config.utils.IdUtil;
import com.service.config.utils.JsonXMLUtils;
import com.service.config.utils.RedisUtil;

import com.service.config.utils.Result;
import com.service.login.dto.UserDto;
import com.service.login.entity.UserLoginRecord;
import com.service.login.service.FeginMstscUnique;
import com.service.login.service.UserLoginRecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;


import static com.service.config.constant.Constant.USER_INFO;

/**
 * @program: CloudCampusService
 * @description: 定时任务
 * @author: rui
 * @create: 2021-03-30 15:35
 **/
@Component
@Async
@Slf4j
public class ScheduleService {

    @Resource
    RedisUtil redisUtil;
    @Resource
    private FeginMstscUnique feginMstscUnique;
    @Resource
    private UserLoginRecordService userLoginRecordService;


    @Scheduled(cron = "0 * */1 * * ?")
   // @Scheduled(fixedDelay  = 20000)
    @Async("taskExecutorConfig")
    public void getLoginUserDispose() throws Exception {
        if (redisUtil.exist(USER_INFO)) {
            List<UserLoginRecord> userLoginRecordList = new ArrayList<>();
            List list = redisUtil.getList(USER_INFO);
            redisUtil.delete(USER_INFO);
            for (Object o : list) {
                Result result = feginMstscUnique.addApiAccount();
                UserDto userDto = JsonXMLUtils.json2obj(o.toString(), UserDto.class);
                UserLoginRecord userLoginRecord = new UserLoginRecord();
                userLoginRecord.setUserId(userDto.getId());
                userLoginRecord.setDate(userDto.getDate());
                userLoginRecord.setOffTime(userDto.getOffTime());
                userLoginRecord.setOnlineTime(userDto.getOnlineTime());
                userLoginRecord.setUsername(userDto.getUsername());
                userLoginRecord.setIp(userDto.getIp());
                userLoginRecord.setTelephone(userDto.getTelephone());
                userLoginRecord.setAddTime(userDto.getAddTime());
                userLoginRecordList.add(userLoginRecord);
                if (result.getCode() == 200) {
                    userLoginRecord.setId(result.getData().toString());
                }else {
                    userLoginRecord.setId(IdUtil.getStringId());
                }
            }
            if (userLoginRecordList.size()>0) {
                userLoginRecordService.insertOrUpdateBatch(userLoginRecordList) ;
            }
        }
    }

}
